<?php
/**
 * Description: 获取直播课详情
 * User: devforma
 * Date: 15/6/6
 * Time: 23:21
 */

class GetCourseDetail implements iController {
    private $now;
    private static $openClassAhead = 600;
    private static $classAhead = 1800;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id'])) {
            return genOutput(1000);
        }

        $course = $cmsdb->getRow('SELECT c.*, q.qq_num, q.web_key FROM `data_live_course` AS c LEFT JOIN `data_qq_group` AS q
        ON c.qq_group_id=q.id WHERE c.id=:cid', array(':cid' => $queryArgs['course_id']));

        if (empty($course))
            return genOutput(1000);

        $alias = $this->getCourseClassNameAlias($queryArgs['course_id']);

        //购买状态
        $isPurchased = false;
        if (!empty($queryArgs['user_id'])){
            if( validateUser($queryArgs) !== 1) {
                return genOutput(1003);//没有授权
            }
            $isPurchased = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:cid
        AND `product_type`="zhiboke" LIMIT 1', array(':uid' => $queryArgs['user_id'], ':cid' => $queryArgs['course_id']));
            $isPurchased = !empty($isPurchased);
        }

        $classIds = getCourseClassIds($queryArgs['course_id']);
        if (empty($classIds))
            return genOutput(1001);

        $this->now = time();
        $date = date('Y-m-d H:i:s', $this->now);

        //获取购买人数
        $personsNum = getCoursePurchasedPersons($queryArgs['course_id']);
        $personsNum = empty($personsNum) ? 0 : intval($personsNum);

        $course->cover_pic = getSecureUrl($course->cover_pic);
        $course->detail_pic = getSecureUrl($course->detail_pic);
        
        //图片、文字介绍
        $images = array();
        $imageText = '';
        if (!empty($course->detail_pic)) {
            if (strpos($course->detail_pic, 'http') !== false) {
                $images = explode(',', $course->detail_pic);
            } else {
                $imageText = nl2br($course->detail_pic);
            }
        }

        $timeCanPurchase = strtotime($course->time_can_purchase);

        //虚拟购买人数
        $extraNumber = $course->id == '1526' ? getExtraPurchasedNum('2016-10-12 18:05:00', 10, 2) : 0;
        $personsNum = intval($personsNum) + $extraNumber;
        if ($course->student_limit != -1 && $personsNum > $course->student_limit) {
            $personsNum = (int)$course->student_limit;
        }

        $data = array(
            'id' => intval($course->id),
            'name' => $course->course_name,
            'is_open' => $course->type_id == 1,
            'qq' => !empty($course->qq_num) ? $course->qq_num : '',
            'qq_key' => !empty($course->web_key) ? $course->web_key : '',
            'intro' => $course->introduction,
            'timeStr' => $course->course_desc,
            'start_time' => '',
            'end_time' => '',
            'can_purchase' => $course->time_can_purchase == '0000-00-00 00:00:00' || $timeCanPurchase <= $this->now ? true : false,
            'can_purchase_time' => date('Y/m/d H:i', $timeCanPurchase),
            'persons_num' => $personsNum,
            'valid_order_num' => $course->is_limited ? getValidOrderNum($course->id, $date) : 0,
            'is_limited' => $course->is_limited ? true : false, //是否是抢购课程
            'price' => floatval($course->price),
            'student_limit' => intval($course->student_limit),
            'is_purchased' => $isPurchased,
            'images' => $images,
            'detail_desc' => $imageText,
            'need_address' => !empty($course->need_address) ? true : false,
            'can_invite' => !empty($course->can_invite) ? true : false,
            'lectors' => array(),
            'classes' => array(),
            'need_eeo' => !empty($course->need_eeo),
            'need_qq' => !empty($course->need_qq),
            'cashback' => intval($course->cashback_fee),
            'invite_code' => $isPurchased && !empty($course->can_invite) ? dechex($queryArgs['user_id']) : '0'
        );

        if (!empty($queryArgs['terminal_type']) && $queryArgs['terminal_type'] === 'pc_web') {
            $data['cover_pic'] = empty($course->cover_pic) ? '' : $course->cover_pic;
            $data['detail_pic'] = $images;
        }

        $exercises = $this->getClassExercises($course->id);

        //获取课堂信息
        $lectors = array();
        $realEndTime = '0000-00-00 00:00:00';
        $realStartTime = '9999-99-99 00:00:00';
        foreach ($classIds as $index => $classId) {
            $class = getLiveClassInfo($classId);

            //开始时间和结束时间设置
            $realEndTime = strcmp($class->end_time, $realEndTime) > 0 ? $class->end_time : $realEndTime;
            $realStartTime = strcmp($class->start_time, $realStartTime) < 0 ? $class->start_time : $realStartTime;

            //课堂状态，区分直播课和公开课
            $status = $course->type_id == 1
                ? $this->getOpenClassStatus(strtotime($class->start_time)-self::$openClassAhead, strtotime($class->end_time))
                : $this->getClassStatus(strtotime($class->start_time)-self::$classAhead, strtotime($class->end_time));

            $data['classes'][] = array(
                'id' => intval($classId),
                'name' => !empty($alias[$classId]) ? $alias[$classId] : $class->class_name,
                'start_time' => $class->start_time,
                'end_time' => $class->end_time,
                'status' => $status,
                'lector' => $class->lector_name,
                'platform' => $class->platform,
                'material' => empty($class->courseware_link) ? '' : $class->courseware_link,
                'exercise_id' => isset($exercises[$classId]) ? $exercises[$classId] : 0,
                'test_id' => empty($class->related_paper_id) ? 0 : intval($class->related_paper_id)
            );

            if (!isset($lectors[$class->lector_id])) {
                $lectors[$class->lector_id] = array(
                    'id' => intval($class->lector_id),
                    'name' => $class->lector_name,
                    'introduction' => $class->introduction,
                    'avatar' => empty($class->avatar) ? '' : $class->avatar,
                    'rate_score' => round($class->grade_score, 1)
                );
            }
        }

        $data['start_time'] = $this->calShowStartTime($realStartTime, $course->course_desc);
        $data['end_time'] = $this->calShowEndTime($realEndTime, $course->course_desc);
        $data['lectors'] = array_values($lectors);
        $data['deadline'] = $course->end_day === '0000-00-00 00:00:00' ? $realEndTime : $course->end_day;

        //eeo课程
        if ($data['need_eeo'] && $isPurchased) {
            $data['eeo_test_status'] = $this->getEEOTest($queryArgs['user_id'], $queryArgs['course_id']);
        }

        return genOutput(1, array(
            'course' => $data
        ));
    }

    /**
     * eeo课程获取客户端测试状态
     *
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @return array
     */
    private function getEEOTest($userId, $courseId) {
        global $uddb;

        $status = [];
        $testLog = $uddb->getRow('SELECT * FROM `eeo_client_test` WHERE `user_id`=:uid AND `course_id`=:cid', [':uid' => $userId, ':cid' => $courseId]);
        if ($testLog) {
            switch ($testLog->status) {
                case '0': //未预约
                    $status['status'] = 'not_scheduled';
                    break;

                case '1': //已预约
                    $status['status'] = 'scheduled';
                    $status['test_time'] = $testLog->test_time;
                    break;

                case '2': //测试中
                    $status['status'] = 'testing';
                    $status['test_id'] = (int)$testLog->id;
                    break;

                case '4': //测试通过
                    $status['status'] = 'success';
                    break;

                case '5': //测试未通过
                    $status['status'] = 'fail';
                    break;
            }
        }

        return $status;
    }

    /**
     * 获取公开课课堂状态
     * @param int $startTime 开始时间戳
     * @param int $endTime 结束时间戳
     * @return string 状态
     */
    private function getOpenClassStatus($startTime, $endTime) {
        if ($startTime > $this->now)
            return 'unstart';
        elseif ($startTime <= $this->now && $this->now <= $endTime)
            return 'on_air';
        elseif ($endTime < $this->now && $this->now <= $endTime + 8*60*60)
            return 'transform';
        elseif ($endTime + 8*60*60 < $this->now && $this->now <= $endTime + 7*24*60*60)
            return 'replay';
        else
            return 'end';
    }

    /**
     * 获取课程状态
     * @param int $startTime 开始时间戳
     * @param int $endTime 结束时间戳
     * @return string
     */
    private function getClassStatus($startTime, $endTime) {
        if ($startTime > $this->now)
           return 'unstart';
        elseif ($startTime <= $this->now && $this->now <= $endTime)
            return 'on_air';
        else
            return 'replay';
    }

    /**
     * 计算供显示的开始时间(由课堂开始时间和手填的课程时间说明(格式:2015.01.10[-2015.04.12])共同决定)
     *
     * @param string $classStartTime 课堂开始时间
     * @param string $courseDateDesc 手填的课程时间说明
     * @return mixed
     */
    private function calShowStartTime($classStartTime, $courseDateDesc) {
        $times = explode('-', $courseDateDesc);
        $times[0] = str_replace('.', '-', $times[0]);

        $t = strtotime($times[0]);

        return $t == false ? $classStartTime : date('Y-m-d H:i:s', $t);
    }

    /**
     * 计算供显示的结束时间(由课堂开始时间和手填的课程时间说明(格式:2015.01.10[-2015.04.12])共同决定)
     *
     * @param string $classEndTime 课堂结束时间
     * @param string $courseDateDesc 手填的课程时间说明
     * @return mixed
     */
    private function calShowEndTime($classEndTime, $courseDateDesc) {
        $times = explode('-', $courseDateDesc);
        if (!isset($times[1]))
            return $classEndTime;

        $times[1] = str_replace('.', '-', $times[1]);
        $t = strtotime($times[1]);

        return $t == false ? $classEndTime : date('Y-m-d H:i:s', $t);
    }


    /**
     * 获取课程下课堂别名
     *
     * @param $courseId
     * @return array
     */
    private function getCourseClassNameAlias($courseId) {
        global $cmsdb;

        $classes = (array)$cmsdb->getResults('SELECT `class_id`, `alias` FROM `relationship_live_class_and_course` WHERE `course_id`=:cid', array(':cid' => $courseId));

        $list = [];
        foreach ($classes as $class) {
            $list[$class->class_id] = $class->alias;
        }

        return $list;
    }


    /**
     * 获取课堂作业
     *
     * @param int $courseId 课程id
     * @return array
     */
    private function getClassExercises($courseId) {
        global $cmsdb;

        $exercises = (array)$cmsdb->getResults('SELECT `id`, `class_id` FROM `data_primary_exercise` WHERE `course_id`=:cid', array(':cid' => $courseId));

        $list = array();
        foreach ($exercises as $e) {
            if ($e->class_id)
                $list[$e->class_id] = (int)$e->id;
        }

        return $list;
    }
}